package sg.techstudio.suntec.validator;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.stereotype.Component;

import sg.techstudio.suntec.object.UserObj;

@Component
public class UserObjValidator {
	private static final Log log = LogFactory.getLog(UserObjValidator.class);
	private static final Pattern EMAIL_PATTERN = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b", Pattern.CASE_INSENSITIVE);
	
	public void validateAdd(UserObj u, ValidationContext context) {
		log.debug("validateAdd() entry");
		MessageContext messages = context.getMessageContext();
		validateCommonField(u, messages);
		if(StringUtils.isBlank(u.getPassword()))
			messages.addMessage(new MessageBuilder().error().source("password")
					.code("required.field").build());
	}
	
	public void validateEdit(UserObj u, ValidationContext context) {
		log.debug("validateEdit() entry");
		MessageContext messages = context.getMessageContext();
		validateCommonField(u, messages);
	}

	private void validateCommonField(UserObj u, MessageContext messages) {
		log.debug("validateCommonField() entry");
		if(StringUtils.isBlank(u.getUsername()))
			messages.addMessage(new MessageBuilder().error().source("username")
					.code("required.field").build());
		if(StringUtils.isBlank(u.getEmail()))
			messages.addMessage(new MessageBuilder().error().source("email")
					.code("required.field").build());
		else if(!EMAIL_PATTERN.matcher(u.getEmail()).matches())
			messages.addMessage(new MessageBuilder().error().source("email")
					.code("invalid.email").build());
	}
}
